package com.jeeplus.modules.common.excel.core;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.formula.functions.T;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * @author wang.yishu
 * @version 1.0
 * @className ExcelImportListener
 * @description Excel导入监听器
 * @date 2022/8/12 17:54
 */
public class ExcelImportListener<T> extends AnalysisEventListener<T> {
    public static int BATCH_COUNT = 100;

    public List<T> importData;

    public Map<Integer, String> headMap;

    private final Consumer<List<T>> consumer;

    public ExcelImportListener(Consumer<List<T>> consumer) {
        this.importData = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        this.consumer = consumer;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        importData.add(t);
        if (this.importData.size() >= BATCH_COUNT) {
            this.consumer.accept(this.importData);
            this.importData = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (CollectionUtils.isNotEmpty(this.importData)) {
            this.consumer.accept(this.importData);
        }
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headMap = headMap;
    }

    public List<T> getImportData() {
        return importData;
    }

    public Map<Integer, String> getHeadMap() {
        return headMap;
    }
}
